package net.thermetics.fx.controllers;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Set;

import net.thermetics.fx.auth.GaeUser;
import net.thermetics.fx.auth.GaeUserAuthentication;
import net.thermetics.fx.auth.UserRegistry;
import net.thermetics.fx.auth.GaeUser.AppRole;
import net.thermetics.fx.forms.RegistrationForm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.users.UserServiceFactory;

@Controller
@RequestMapping("/register")
public class RegistrationController {
	@Autowired
	private UserRegistry registry;
	
	@RequestMapping(method = RequestMethod.GET)
	public String loadForm(Model model) {
		model.addAttribute("submission", new RegistrationForm());
		return "register";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(RegistrationForm form, BindingResult result) {
	    if (result.hasErrors()) {
	        return null;
	    }

	    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    GaeUser currentUser = (GaeUser)authentication.getPrincipal();
	    Set<AppRole> roles = EnumSet.of(AppRole.USER);

	    if (UserServiceFactory.getUserService().isUserAdmin()) {
	        roles.add(AppRole.ADMIN);
	    }

	    GaeUser user = new GaeUser(currentUser.getUserId(), currentUser.getNickname(), currentUser.getEmail(),
	            roles, false, true, new HashMap<String, String>(), "");

	    registry.persistUser(user);

	    // Update the context with the full authentication
	    SecurityContextHolder.getContext().setAuthentication(new GaeUserAuthentication(user, authentication.getDetails()));

	    return "redirect:/";
	}

}
